package com.z.controller.verification;

import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.utils.CaptchaUtil;
import com.z.result.ResultWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/easy-captcha")
public class EasyCaptchaController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @GetMapping("/get-code")
    public ResultWrapper getCode(HttpServletRequest request, HttpServletResponse response){

        SpecCaptcha specCaptcha = new SpecCaptcha(100, 50);

        // 获取验证码数值
        String text = specCaptcha.text();
        System.out.println("验证码：" + text);

        // 生成redis key
        String uuid = UUID.randomUUID().toString();
        request.getSession().setAttribute("codeId",uuid);

        // 存取
        stringRedisTemplate.opsForValue().set(uuid,text,60,TimeUnit.SECONDS);

        // Base64 编码验证码
        String code = specCaptcha.toBase64();
        System.out.println("code" + code);

        // 封装
        Map<String,String> map = new HashMap<>();
        map.put("encode","base64");
        map.put("code",code);

        return ResultWrapper.getSuccessBuilder().data(map).build();




    }

    @GetMapping("/verify/{code}")
    public ResultWrapper verify(@PathVariable("code") String verifyCode, HttpServletRequest request) {

        String sessionId = (String) request.getSession().getAttribute("codeId");

        String code =stringRedisTemplate.opsForValue().get(sessionId);

        if (verifyCode.equals(code)){

            return ResultWrapper.getSuccessBuilder().msg("验证通过").build();
        }

       return ResultWrapper.getFailBuilder().msg("验证失败").build();
    }


}
